import os
import gradio as gr
import requests
import json
import subprocess
import threading
import openai_api_request

command = ["python", "openai_api_server.py"]
process = subprocess.Popen(
    command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)


def read_process_output(process):
    """Reads the process output and prints it."""
    while True:
        output = process.stdout.readline()
        if output == '' and process.poll() is not None:
            break
        if output:
            print("API Server: "+output.strip())


# 启动一个线程读取 subprocess 输出
thread = threading.Thread(target=read_process_output, args=(process,))
thread.start()

system_prompt = {
    "role": "system",
    "content":
    "你是一个幽默的助手，遵守中国法律、道德。不回答任何政治等违法敏感问题。"
}


def chat(message, history):
    messages = [system_prompt]
    for msg in history:
        messages.append({"role": "user", "content": str(msg[0])})
        messages.append({"role": "assistant", "content": str(msg[1])})

    messages.append({"role": "user", "content": str(message)})

    complete_message = ''

    res = openai_api_request.simple_chat(messages=messages, use_stream=True)
    for chunk in res:
        delta_content = chunk.choices[0].delta.content
        complete_message += delta_content
        # print(delta_content, end='')  # 不换行拼接输出当前块的内容
        yield complete_message  # gradio 需要返回完整可迭代内容
    print(message)
    print("\nComplete message:", complete_message)


chatbot = gr.Chatbot(height=450, label="glm4")
with gr.Blocks(theme=gr.themes.GoogleFont("aaa"), fill_height=True) as demo:
    chat = gr.ChatInterface(chat,
                            submit_btn="提交",
                            chatbot=chatbot,
                            clear_btn="清空",
                            stop_btn="暂停",
                            undo_btn=None,
                            retry_btn="重试",
                            examples=["作为人工智能，你对未来科技的发展趋势有什么看法？",
                                      "讲个笑话", "今天吃什么？", "生鱼片是死鱼片吗？", "介绍中国思想史", '如果可以，你最想做什么？'],
                            )
    # with gr.Row():
    #     useStage = gr.Textbox(lines=2, label="使用信息", placeholder="", input="")
demo.queue()
demo.launch(show_api=False)
